<template>
  <div class="v-prefix-textarea">
    <span v-if="encrypted">{{ desensitize(text) }}</span>
    <template v-else>
      <div class="v-editor-textarea">
        <el-input
          v-if="selected"
          v-model="text"
          :style="{ height: editDivHeight }"
          :maxlength="20"
          :disabled="row.readonly || isModelDisabled"
          :inputStyle="{ minHeight: '24px' }"
          @change="handelChange"
        />
        <div
          v-if="!selected"
          ref="showDiv"
          style="padding: 3px 2px"
        >
          {{ text }}
        </div>
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { BusEvent } from "@/constants/Enums";
import { modelService } from "@/modules/model/service";
import { ref, watch, Ref, inject } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { PropertyRow } from "../../types";
import { desensitize } from "@/util/common";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  encrypted?: boolean;
  editDivHeight?: number;
  maxlength?: number;
}>();

const text = ref(props.row.value as string);
let showDiv = ref<HTMLElement>();
let editDivHeight = ref(props.editDivHeight ? Math.max(props.editDivHeight, 24) + "px" : "24px");

watch(
  () => props.row.value,
  newVal => (text.value = newVal as string)
);
watch(
  () => props.selected,
  newVal => {
    // 从非编辑状态进入编辑状态，将显示时候的高度复制给编辑状态的div
    if (newVal && showDiv.value) {
      const height = Math.max(showDiv.value.clientHeight, 24) + "px";
      editDivHeight.value = height;
    }
  }
);

const handelChange = async () => {
  text.value = text.value.trim();
  const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(props.row, app.activeProject!.id);
  dto.value = text.value;
  let res = await modelService.updateModelProperty(dto);

  if (res) {
    app.$bus.emit(BusEvent.REFRESH_POPERTY, props.row.modelId);
  }
};
</script>

<style lang="scss">
.v-prefix-textarea {
  // overflow: ;
  padding-left: 5px;
  display: flex;
  .v-editor-textarea {
    flex: 1 1 100px;
    .el-textarea__inner {
      height: 100%;
      font-size: 11px;
      line-height: 24px;
      resize: none;
    }
  }
  > .img-btn {
    display: flex;
    align-items: center;
    // margin-top: 4px;
    flex: 0 0 auto;
    width: 24px;
  }
}
</style>
